<template>
    <div class="history-container">
        <div class="history-sidebar" :class="{ collapsed: isCollapsed }">
            <div class="sidebar-header">
                <el-button class="new-chat-btn" type="primary" @click="handleNewChat">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <span v-show="!isCollapsed">新建对话</span>
                </el-button>
            </div>
            <div class="history-list" v-show="!isCollapsed">
                <template v-if="historyList.length > 0">
                    <div v-for="item in historyList" :key="item.session_id" class="history-item" :class="{ active:  currentHistory === item.session_id }" @click="handleSelectHistory(item)">
                        <div class="item-content">
                            <!-- <div class="question">{{ item.desc }}</div> -->
                            <div class="meta">
                                <span class="time" :title="item.desc">{{ item.desc? item.desc : '...' }}</span>
                                <el-dropdown trigger="click" @command="handleCommand($event, item)">
                                    <div class="history-item-more" @click.stop>
                                        <el-icon>
                                            <More />
                                        </el-icon>
                                    </div>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="delete">
                                                <el-icon>
                                                    <Delete />
                                                </el-icon>
                                                <span>删除</span>
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </div>
                    </div>
                </template>
                <div v-else class="empty-state">
                    <el-empty description="暂无历史记录" />
                </div>
                <div style="text-align: center;display: none;" id="loading">加载中...</div>
            </div>
        </div>

        <!-- 折叠按钮 -->
        <div class="collapse-btn" @click="toggleCollapse">
            <el-icon>
                <ArrowRight v-if="!isCollapsed" />
                <ArrowLeft v-else />
            </el-icon>
        </div>
        <div class="history-content">
            <home-view v-if="!isNewChat" :key="!isNewChat" :history-question="currentHistory?.desc" @search="handleHomeSearch" />
            <dialo-gue v-else :files_appendixobj="files_appendixobj" :key="isNewChat" :enddata="enddata" @changestop="changestop" @updateonUnmounted="updateonUnmounted" @succseechat="handlesuccseechat" :dialogues="dialogues" :currentHistory="currentHistory ? currentHistory : sessionId" :initialQuestion="initialQuestion" @CLEARSEARCH="CLEARSEARCH"></dialo-gue>
        </div>
    </div>
</template>

<script>
export default {
    name: 'HistoryView'
}
</script>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Delete, Plus, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage, ElButton } from 'element-plus'
import HomeView from '../HomeView.vue'
import DialoGue from '../dialogue/index.vue'
import { crosslist, crossinfo, agree_msg, disagree_msg, delete_msg, delete_session, summary_title } from "@/api/historycross"


const isNewChat = ref(false) // 是否是新聊天
const isCollapsed = ref(true)

// 对话记录 左侧列表
const historyList = ref([])
// 当前选中的历史记录id
const currentHistory = ref(null)
// 传给子组件的历史记录
const dialogues = ref(null)
// 最新对话记录 给点赞用的
const enddata = ref(null)
// session 下拉加载
const queryParams = reactive({
    limit: 20,
    last_time: null,
})
// 新窗口生成sessionId
let sessionId = null
sessionId = generateSessionId();  // 使用函数生成一个唯一的 sessionId
function generateSessionId() {
    return Date.now() + Math.floor(Math.random() * 1000);  // 当前时间戳 + 随机数
}
// 开始新聊天
const handleNewChat = () => {
    currentHistory.value = null
    isNewChat.value = false
    sessionId = generateSessionId();
}
// 获取历史记录
const getcrosslist = async () => {
    const response = await crosslist(queryParams)
    historyList.value = response.data
    historyList.value.forEach(item => {
        item.desc = item.desc.replace(/\\n/g, ' ')
    })
}
// 选择历史记录
const handleSelectHistory = (item) => {
    currentHistory.value = item.session_id
    isNewChat.value = true
    // 这里可以添加加载历史对话的逻辑
    gethistorydetail(item.session_id)
}
// 查询对话历史记录的详情
const gethistorydetail = async (sessionId) => {
    const result = await crossinfo({
        session_id: sessionId
    })
    dialogues.value = []
    dialogues.value = result.data.dialogues
}


// 对话记录 处理下拉菜单命令-删除
const handleCommand = (command, item) => {
    switch (command) {
        case 'delete':
            ElMessageBox.confirm(
                '确定要删除这条历史记录吗？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(async () => {
                try {
                    const result = await delete_session({
                        session_id: item.session_id
                    })
                    if (result.code == 200) {
                        ElMessage.success('删除成功')
                        queryParams.last_time = null
                        queryParams.limit = 20
                        getcrosslist()
                        // 如果删除的是当前选中的会话，则返回首页
                        if (currentHistory.value === item.session_id) {
                            handleNewChat()
                        }
                    }

                } catch (error) {
                    // ElMessage.error('删除失败')
                }
            }).catch(() => { })
    }
}
const initialQuestion = ref(null)
const files_appendixobj = ref([])
// 处理搜索事件
const handleHomeSearch = (searchobj) => {
    isNewChat.value = true
    initialQuestion.value = searchobj.val
    // files_appendixobj.value = searchobj.files_appendix
}
const CLEARSEARCH = (searchText) => {
    initialQuestion.value = null
}
let intervalId = null;
// 对话完成后的处理 
const handlesuccseechat = async (chatInfo) => {
    /* 是新窗口 */
    if (!currentHistory.value) {
        queryParams.last_time = null
        queryParams.limit = 20
        await getcrosslist()
        currentHistory.value = historyList.value[0].session_id
        historyList.value[0].desc = ''
        intervalId = setInterval(() => {
            summary_title({ session_id: currentHistory.value }).then(result => {
                if (result.code == 200) {
                    historyList.value[0].desc = result.data
                    if (result.data) {
                        clearInterval(intervalId)
                    }
                }
            })
        }, 1000);
    }
    newsdetailsId()
}
// 在未回答完时做出了切换
const updateonUnmounted = () => {
    getcrosslist()
}
// 当新窗口回答一半时的停止
const changestop = async (e) => {
    handlesuccseechat()
}
// 历史最新的对话id
const newsdetailsId = async () => {
    const result = await crossinfo({
        session_id: currentHistory.value ? currentHistory.value : sessionId
    })

    enddata.value = []
    enddata.value = result.data.dialogues[result.data.dialogues.length - 1]
}
// 切换侧边栏折叠状态
const toggleCollapse = () => {
    isCollapsed.value = !isCollapsed.value
}


let timer = null
// 事件处理函数
const handleResize = () => {
    const content = document.querySelector('.history-list');
    content.addEventListener('scroll', (e) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            if (Math.round(content.scrollTop + content.clientHeight) >= content.scrollHeight) {
                loadMore();
            }
        }, 500); // 设置节流的时间间隔
    });
};
async function loadMore() {
    const loading = document.getElementById('loading');
    loading.style.display = 'block';  // 显示加载状态
    queryParams.limit = 10
    queryParams.last_time = historyList.value[historyList.value.length - 1].create_time
    const response = await crosslist(queryParams)
    if (response.code == 200) {
        historyList.value = historyList.value.concat(response.data)
        historyList.value.forEach(item => {
            item.desc = item.desc.replace(/\\n/g, ' ')
        })
        loading.style.display = 'none';
        clearTimeout(timer);
    }
    if (response.data.length == 0) {
        loading.style.display = 'block';  // 显示加载状态
        loading.innerText = '没有更多数据了'
    }
}

onMounted(async () => {

    // await getcrosslist()
    // if (historyList.value.length > 0) {
    //     currentHistory.value = historyList.value[0].session_id
    //     isNewChat.value = true
    //     handleSelectHistory(historyList.value[0])
    // }    // // window.addEventListener('resize', handleResize);
    // handleResize()


})
onUnmounted(() => {
    clearInterval(intervalId)
    // window.removeEventListener('resize', handleResize);
})
</script>

<style lang="scss" scoped>
.history-container {
    display: flex;
    height: 100%;
    background: #fff;
    position: relative;

    .history-sidebar {
        width: 300px;
        border-right: 1px solid #e8e8e8;
        display: flex;
        flex-direction: column;
        transition: width 0.3s ease;
        padding: 0 0 5px 0;
        &.collapsed {
            width: 80px;

            .new-chat-btn {
                padding: 8px;
                justify-content: center;
            }
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e8e8e8;

            .new-chat-btn {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 8px 16px;
                background: #0078f8;
                border-color: #0078f8;
                transition: all 0.2s ease;

                &:hover {
                    background: #0078f8;
                    transform: scale(1.02);
                }
            }
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
            padding: 16px;

            .history-item {
                padding: 16px;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.3s;
                margin-bottom: 8px;

                &:hover {
                    background: #f5f7fa;
                }

                &.active {
                    background: #e6f4ff;
                    border-left: 3px solid #6751f0;
                }

                .item-content {
                    .question {
                        font-size: 14px;
                        color: #333;
                        margin-bottom: 8px;
                        line-height: 1.4;
                        // 多行文本省略
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                    }

                    .meta {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .time {
                            font-size: 14px;
                            color: #333;
                            // 多行文本省略
                            display: -webkit-box;
                            -webkit-box-orient: vertical;
                            -webkit-line-clamp: 1;
                            overflow: hidden;
                        }
                    }
                }
            }

            .empty-state {
                padding: 40px 20px;
                text-align: center;
                color: #999;
            }
        }
    }

    .collapse-btn {
        position: absolute;
        left: 300px;
        top: 30%;
        transform: translateY(-50%);
        width: 20px;
        height: 50px;
        background: #fff;
        border: 1px solid #e8e8e8;
        border-left: none;
        border-radius: 0 4px 4px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 10;
        transition: left 0.3s ease;

        &:hover {
            background: #f5f7fa;
        }

        .el-icon {
            font-size: 16px;
            color: #666;
        }
    }

    &:has(.history-sidebar.collapsed) {
        .collapse-btn {
            left: 80px;
        }
    }

    .history-content {
        flex: 1;
        // background: #E4F1FF;
        position: relative;
        height: 100vh;
        overflow: hidden;
    }
}
/* 设置滚动条整体宽度 */
::-webkit-scrollbar {
    width: 10px; /* 垂直滚动条宽度 */
    height: 10px; /* 水平滚动条高度 */
}

/* 设置滚动条轨道样式 */
::-webkit-scrollbar-track {
    background-color: #f1f1f1; /* 轨道背景颜色 */
    border-radius: 10px; /* 轨道圆角 */
}

/* 设置滚动条滑块样式 */
::-webkit-scrollbar-thumb {
    background-color: #d0d0d0; /* 滑块颜色 */
    border-radius: 10px; /* 滑块圆角 */
    border: 2px solid #f1f1f1; /* 滑块与轨道之间的间隔 */
}

/* 设置滑块在悬停时的样式 */
::-webkit-scrollbar-thumb:hover {
    background-color: rgb(211, 211, 211) 0d0; /* 悬停时的滑块颜色 */
}
</style> 